<template>
  <div class="toosl-card">
    <ul>
      <li
        v-for="(item, index) in tools"
        :key="index"
        @click="handleClick(index)"
        :class="{ active: isSateOn && index === activeIndex }"
      >
        <i :class="['iconfont', `icon-${item.icon}`]"></i>
        <span>{{ item.title }}</span>
        <el-divider direction="vertical" v-if="index !== tools.length - 1" border-style="dashed" />
      </li>
    </ul>
  </div>
</template>

<script setup>
import { ref, inject } from 'vue'
// import axios from 'axios'

const map = inject('map')
const AMap = inject('AMap')
let activeIndex = ref(null) //当前选中的索引

//卫星图部分
const isSateOn = ref(false) //判断切换的状态
let sateLayer = ref(null) //卫星图层实例
let roadNetLayer = ref(null) //路网图层实例

//空气质量部分
const isAirOn = ref(false) //判断切换的状态
let center = ref(null) //存储中心点的经纬度
let geocoder = ref(null) //逆向地理编码实例
let cityName = ref(null) //存储城市名称
let airData = ref(null) //存储空气质量数据
let airChart = ref(null) //空气质量图表实例

//路况部分
const isTrafficOn = ref(false) //判断切换的状态
let trafficLayer = ref(null) //路况图层实例

//测距部分
let mouseTool = ref(null) //测距工具实例
let isMouseToolOn = ref(false) //判断切换的状态

//全屏部分
let isFullScreen = ref(false)

//工具点击的函数
const handleClick = (index) => {
  switch (index) {
    case 0: //卫星
      switchSate()
      activeIndex.value = index
      break
    case 1: //空气
      activeIndex.value = index
      switchAir()
      break
    case 2: //路况
      activeIndex.value = index
      switchTraffic()
      break
    case 3: //测距
      activeIndex.value = index
      switchMouseTool()
      break
    case 4: //全屏
      activeIndex.value = index
      fullScreen()
      break
  }
}

//切换卫星图的方法
const switchSate = () => {
  // console.log(isSateOn.value)

  if (!isSateOn.value) {
    //卫星图打开的状态
    sateLayer.value = new AMap.value.TileLayer.Satellite()
    roadNetLayer.value = new AMap.value.TileLayer.RoadNet()
    map.value.add([sateLayer.value, roadNetLayer.value])
  } else {
    // 关闭卫星图
    if (sateLayer.value || roadNetLayer.value) {
      map.value.removeLayer(sateLayer.value)
      map.value.removeLayer(roadNetLayer.value)
    }
  }
  isSateOn.value = !isSateOn.value
}

//空气的方法
//获取中心点的经纬度,逆向地理编码提取出市,再根据市获取空气质量数据
const switchAir = async () => {
  if (!isAirOn.value) {
    center.value = [map.value.getCenter().lng, map.value.getCenter().lat]
    // console.log(map.value.getCenter())
    // console.log(center.value)
    geocoder.value = new AMap.value.Geocoder()
    await geocoder.value.getAddress(center.value, (status, result) => {
      if (status === 'complete' && result.info === 'OK') {
        // console.log(result)
        // console.log(result)
        cityName.value = result.regeocode.addressComponent.city
        // console.log(cityName.value)
      }
      if (cityName.value) {
        cityName.value = cityName.value.replace('市', '')
        // console.log(cityName.value)
        // getAirData(cityName.value)
        airData.value = JSON.parse(localStorage.getItem('airData'))
        // console.log(airData.value)
        for (let i = 0; i < airData.value.length; i++) {
          if (airData.value[i].lat || airData.value[i].lng) {
            // console.log(typeof `${airData.value[i].city} ${airData.value[i].AQI}`)
            console.log(`${airData.value[i].lon}`, `${airData.value[i].lat}`)
            airChart.value = new AMap.value.Text({
              text: `${airData.value[i].city} ${airData.value[i].AQI}`,
              anchor: 'bottom-left',

              draggable: false,
              cursor: 'pointer',
              style: {
                border: '1px solid #000',
                padding: '5px',
                'border-radius': '50px 50px 50px 0px',
              },
              position: [`${airData.value[i].lon}`, `${airData.value[i].lat}`],
            })
            airChart.value.setMap(map.value)
          }
        }
      }
    })
  } else {
    if (airChart.value) {
      map.value.clearMap()
      airChart.value = null
    }
  }
  isAirOn.value = !isAirOn.value
}

// //空气质量请求的方法
// const getAirData = (cityName) => {
//   const apiUrl = '/air/environment/air/cityair' // 接口请求URL
//   const apiKey = '2e500e4e643e208a2da462c733c9e174' // 在个人中心->我的数据,接口名称上方查看

//   // 接口请求入参配置
//   const requestParams = {
//     key: apiKey,
//     city: cityName,
//   }
//   axios
//     .get(apiUrl, { params: requestParams })
//     .then((response) => {
//       // 解析响应结果
//       if (response.status === 200) {
//         // console.log(cityName)
//         // console.log(response)
//         const responseResult = response.data
//         // 网络请求成功。可依据业务逻辑和接口文档说明自行处理。
//         responseResult.result[0].lastMoniData
//         airData.value = Object.values(responseResult.result[0].lastMoniData)
//         //先存在本地调试用
//         localStorage.setItem('airData', JSON.stringify(airData.value))
//       } else {
//         // 网络异常等因素，解析结果异常。可依据业务逻辑自行处理。
//         console.log('请求异常')
//       }
//     })
//     .catch((error) => {
//       // 网络请求失败，可以根据实际情况进行处理
//       console.log('网络请求失败:', error)
//     })
// }

//切换交通图层的方法
const switchTraffic = () => {
  if (!isTrafficOn.value) {
    trafficLayer.value = new AMap.value.TileLayer.Traffic()
    map.value.add(trafficLayer.value)
  } else {
    if (trafficLayer.value) {
      map.value.removeLayer(trafficLayer.value)
    }
  }
  isTrafficOn.value = !isTrafficOn.value
}

//测距的方法
const switchMouseTool = () => {
  if (!isMouseToolOn.value) {
    mouseTool.value = new AMap.value.MouseTool(map.value)
    mouseTool.value.rule({
      startMarkerOptions: {
        //设置量测起始点标记属性对象 可缺省
        icon: new AMap.value.Icon({
          size: new AMap.value.Size(19, 31), //图标大小
          imageSize: new AMap.value.Size(19, 31),
          image: '//webapi.amap.com/theme/v1.3/markers/b/start.png',
        }),
        offset: new AMap.value.Pixel(-9, -31),
      },
      endMarkerOptions: {
        //设置量测结束点标记属性对象 可缺省
        icon: new AMap.value.Icon({
          size: new AMap.value.Size(19, 31), //图标大小
          imageSize: new AMap.value.Size(19, 31),
          image: '//webapi.amap.com/theme/v1.3/markers/b/end.png',
        }),
        offset: new AMap.value.Pixel(-9, -31),
      },
      midMarkerOptions: {
        //设置拖拽路线插件途经点点标记属性对象 可缺省
        icon: new AMap.value.Icon({
          size: new AMap.value.Size(19, 31), //图标大小
          imageSize: new AMap.value.Size(19, 31),
          image: '//webapi.amap.com/theme/v1.3/markers/b/mid.png',
        }),
        offset: new AMap.value.Pixel(-9, -31),
      },
      lineOptions: {
        //可缺省
        strokeStyle: 'solid',
        strokeColor: '#FF33FF',
        strokeOpacity: 1,
        strokeWeight: 2,
      },
    })
    mouseTool.value.on('draw', () => {
      // console.log('绘制完成')
      mouseTool.value.close(false)
    })
    // } else {
    //   if (mouseTool.value) {
    //     mouseTool.value.close(true)
    //   }
  }
  // isMouseToolOn.value = !isMouseToolOn.value
}

//全屏的方法
const fullScreen = () => {
  const window = document.documentElement
  if (isFullScreen.value) {
    //退出
    document.exitFullscreen()
    isFullScreen.value = false
  } else {
    window.requestFullscreen()
    isFullScreen.value = true
  }
}

// 尝试抽取切换图层的方法
// const switchLayer = (layer,status) => {

// }

const tools = [
  { icon: 'weixing', title: '卫星' },
  { icon: 'kongqizhiliang', title: '空气' },
  { icon: 'lukuang', title: '路况' },
  { icon: 'map-ruler-full', title: '测距' },
  { icon: 'quanping', title: '全屏' },
]
</script>

<style lang="scss" scoped>
.toosl-card {
  position: fixed;
  top: 10px;
  right: 200px;
  height: 50px;
  background: #fff;
  box-shadow: 0 2px 2px rgba(0, 0, 0, 0.15);
  border-radius: 3px;
  padding: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  ul {
    display: flex;
    justify-content: center;
    align-items: center;
    li {
      cursor: pointer;
      color: #555;
      font-size: 12px;
      &:hover {
        color: #aaa;
      }
      &.active {
        color: #80c5ff;
      }
      i {
        margin-right: 5px;
        margin-left: 5px;
      }
      span {
        margin-right: 5px;
      }
    }
  }
}
</style>
